package com.sinosoft.vaccinetoai.server.configure;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * MVC配置
 * @author xzh
 * @date 2022-10-24 12:49
 * @since 1.0.0
 */
@Configuration
public class CustomWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 添加CORS跨域支持
        registry.addMapping("/**")
                // 允许的请求域
                .allowedOrigins("*")
                // 允许的请求方法
                .allowedMethods("*")
                // 允许的请求头
                .allowedHeaders("*")
                // 允许跨域携带Cookie
                .allowCredentials(false);
    }

    /**
     * 自定义JSON格式化
     * @param builder Builder
     * @return {@link ObjectMapper }
     * @author xzh
     * @since 1.0.0
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule simpleModule = new SimpleModule();
        // 将Long类型转为String类型 避免前端直接接收Long类型造成最后两位变成00
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }

}
